# -*- coding: iso-8859-1 -*-
#
#    This is part of Malvinas Argentinas Messenger
#
#    Malvinas Argentinas Messenger is free software; you can redistribute
#    it and/or modify it under the terms of the GNU General Public License
#    as published by the Free Software Foundation; either version 2 of the
#    License, or (at your option) any later version.
#
#    Malvinas Argentinas Messenger is distributed in the hope that it will be
#    useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with Malvinas Argentinas Messenger; if not, write to the Free
#    Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
#    MA  02110-1301  USA

import pymsn
import pymsn.event
from pymsn.profile import Membership
from pymsn.msnp2p.session_manager import *
from pymsn.msnp2p.session import *
from pymsn.msnp2p.constants import EufGuid
import pymsn.util.string_io as StringIO

import gobject
from eventos import *
from utils import *
from contact import Contact
from group import Group
from time import sleep

class Client(pymsn.Client):
	def __init__(self, quit, session, http_mode=False):
		self.session = session
		self.account = (self.session.passport, self.session.password)
		server = ('messenger.hotmail.com', 1863)
		self.quit = quit
		if http_mode:
			from pymsn.transport import HTTPPollConnection
			pymsn.Client.__init__(self, server, get_proxies(), HTTPPollConnection)
		else:
			pymsn.Client.__init__(self, server, proxies = get_proxies())
		self._event_handler = ClientEvents(self)
		gobject.idle_add(self._connect)
		self._invitationEvents_handler = InviteEvents(self)
		self._contactsEvents_handler = ContactEvents(self)
		self._profileEvents_handler = ProfileEvents(self)
		self._addressBookEvents_handler = AddressBookEvents(self)
		self._offlineMessagesEvents_handler = OfflineMessagesEvents(self)
		self._p2p_session_manager = P2PSessionManager(self)
		self.status = 0

	def chgStatus(self, status):
		self.status = status
		self.session.chgStatus(status)

	def _connect(self):
		self.login(*self.account)
		return False

	def sendMsgToClient(self, msg):
		s = self.session.getSocketToClient()
		s.send(msg)
		sleep(.1)

	def setMsnObj(self):
		if int(self.session.config['show_picture']) == 0:
			self.profile.msn_object = None
		else:			
			print "Con MSNOBJECT  - Server Andino"
			"""
			import os
			import sys
			import msnobj
			import time
			os.system("rm " + sys.path[0] + "/picture.tmp")
			os.system("cp " + self.session.config['picture_name'] + " " + sys.path[0] + "/picture.tmp")			
			self.profile.msn_object = msnobj.Msnobj(self.session.passport).msn_object
			"""

			path = self.session.config['picture_name']
			print "Path de display picture: " + path
			f = open(path, 'r')
			old_pos = f.tell()
			f.seek(0, 2)
			size = f.tell()
			f.seek(old_pos,0)
			msn_object = pymsn.p2p.MSNObject(self.profile,
			size, pymsn.p2p.MSNObjectType.DISPLAY_PICTURE, "picture.tmp", "", None, None, f)
			#FIXME
			print msn_object

			self.profile.msn_object = msn_object
			#f.close()

	def memberships(self, mem):
		m = []
		if mem & Membership.NONE:
			m.append('NONE')
		if mem & Membership.FORWARD:
			m.append('FORWARD')
		if mem & Membership.ALLOW:
			m.append('ALLOW')
		if mem & Membership.BLOCK:
			m.append('BLOCK')
		if mem & Membership.REVERSE:
			m.append('REVERSE')
		if mem & Membership.PENDING:
			m.append('PENDING')
		return m

	def getContacts(self):
		contactos = []
		if self.status == pymsn.event.ClientState.OPEN:
			for c in \
			self.address_book.contacts.search_by_presence("NLN") | \
			self.address_book.contacts.search_by_presence("BRB") | \
			self.address_book.contacts.search_by_presence("PHN") | \
			self.address_book.contacts.search_by_presence("LUN") | \
			self.address_book.contacts.search_by_presence("BSY") | \
			self.address_book.contacts.search_by_presence("AWY") | \
			self.address_book.contacts.search_by_presence("IDL"):
				con = Contact(c.account, c.presence, c.display_name, c.personal_message, c.current_media, self.memberships(c.memberships), self.buildGroups(c.groups))
				contactos.append(con)
		return self.sortContactList_Nick(contactos)

	def sortContactList_Nick(self, lista):
		lista.sort(key=lambda obj: obj.nick)
		return lista

	def sortContactList_Status(self, lista):
		lista.sort(self.compare)
		return lista

	# Funcion para ordenar la lista de contactos en funcion de estado y nicknames.
	def compare(self, x, y):
		prioridades = {"NLN" : "1", "BRB" : "2", "PHN" : "2", "LUN" : "2", "BSY" : "3", "AWY" : "4", "IDL" : "4", "HDN" : "5", "FLN" : "6"}
		res = -1
		if prioridades[x.status] > prioridades[y.status]:
			res = 1
		elif prioridades [x.status] == prioridades [y.status] and x.nick > y.nick:
			res = 1
		return res

	def getGroups(self):
		return self.buildGroups(self.address_book.groups)
		
	def buildGroups(self, lista):
		grupos = []
		for g in lista:
			grupos.append(Group(g.id, g.name))
		grupos.sort(key=lambda obj: obj.name)
		return grupos

	def getContact(self, contacto):
		for c in self.address_book.contacts.search_by_account(contacto):
			return Contact(contacto, c.presence, c.display_name, c.personal_message, c.current_media, self.memberships(c.memberships), self.buildGroups(c.groups))

	def prueba(self):
		return self.getGroups

	def chat(self, account, ctime, msg):
		c = self.address_book.contacts.search_by_account(account)
		conv = self.session.getConversation(account)
		#if conv.pconv is not None: print conv.pconv._switchboard_requested
		if conv.pconv is not None and conv.pconv._switchboard_requested == False and \
		not len(self.session.getPendingMsg(account)):
			formatting = pymsn.TextFormat("Comic Sans MS", pymsn.TextFormat.UNDERLINE | pymsn.TextFormat.BOLD, 'FF0000')
			conv.pconv.send_text_message(pymsn.ConversationMessage(msg, formatting))
			conv.text.append((ctime, "O", msg.encode(self.session.config['encoding'])))
			return "OK"
		if conv.pconv is None:		
			conv.pconv = pymsn.Conversation(self, c)
			conv.events = ConversationEvents(conv.pconv)
			conv.events.client = self
		conv.pendientes.append((ctime, msg))
		return "WAIT"
